package com.example.hms.util;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@Configuration
public class TokenInter implements HandlerInterceptor {
    private long refreshTime = 1000 * 60 * 60 * 3; // TOKEN过期时间为3小时


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        String userName = (String) session.getAttribute("userName");
        if (userName == null || userName.equals("")) {
            returnJson(response, JSONCreate("账户未登录"));
            return false;
        } else {
            Map<String, Object> map = TokenUtil.checkToken((String) session.getAttribute("token"));
            if (!map.get("userName").equals(userName)) {
                returnJson(response, JSONCreate("账户信息错误，请重新登录"));
                return false;
            } else {
                if (System.currentTimeMillis() - (Long) map.get("time") > refreshTime) {
                    returnJson(response, JSONCreate("TOKEN过期，请重新登录"));
                    return false;
                } else {
                    return true;
                }
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HttpSession session = request.getSession();
        String userId = ((Integer) session.getAttribute("userId")).toString();
        String userName = (String) session.getAttribute("userName");
        String roleName = (String) session.getAttribute("roleName");
        Long time = System.currentTimeMillis();
        session.setAttribute("token", TokenUtil.getToken(userId,userName,roleName,time));
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("视图渲染完毕");
    }

    private void returnJson(HttpServletResponse response, String result) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(result);
        } catch (IOException e) {
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    private String JSONCreate(String message) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("{\"code\":-1,\"message\":\"");
        stringBuffer.append(message);
        stringBuffer.append("\"}");
        return stringBuffer.toString();
    }


}

